package web

import (
	"net/http"
	"strings"
	"fmt"
)

/**
过滤器的签名
 */
type FilterHandler func(writer http.ResponseWriter, request *http.Request) error

//拦截uri映射处理
var filterMapping = make(map[string]FilterHandler,0)
//保证有序uri
var uriArray = make([]string,0)

/**
注册拦截器的操作
uriRule 拦截规则 后缀是/*
fn 拦截的处理函数
 */
func Register(uriRule string, fn FilterHandler)  {
	uriRule = uriRule[:len(uriRule) - 1]
	filterMapping[uriRule] = fn
	uriArray = append(uriArray, uriRule)
}


/**
web 接口服务的签名
主要是处理可以拦截的请求
 */
type WebHandler func(writer http.ResponseWriter, request *http.Request)

func Handle(webHandler WebHandler) func(writer http.ResponseWriter, request *http.Request) {
	return func(writer http.ResponseWriter, request *http.Request) {
		var url = request.RequestURI
		for _,v := range uriArray{
			if strings.Contains(v, url) {
				fmt.Println(v)
				e := filterMapping[v](writer,request)
				if e != nil {
					writer.Write([]byte(e.Error()))
					return 
				}
			}
		}
		
		webHandler(writer,request)
	}
}